package com.example.blog.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    //long EXPIATION_TIME = 7*24*60*60*1000;//7天
    private static final long EXPIATION_TIME = 7*24*60*60*1000;//7天
    private static final String secreString = "rNwAoNAr1OsREe5M3QBis1WT3Ovbwhnjs6THcyRLtgA=";
    private static final Key key = Keys.hmacShaKeyFor(secreString.getBytes(StandardCharsets.UTF_8));


    /**
     * 生成令牌
     */

    public static String genJwt(Map<String,Object> map){
        return Jwts.builder()
                .setClaims(map)
                .signWith(key, SignatureAlgorithm.HS256)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIATION_TIME))
                .compact();
    }

    /**
     * 校验令牌
     */
    public static Boolean check(String token){
        if (!StringUtils.hasLength(token)){
            return false;
        }

        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        try {
            Claims body = build.parseClaimsJws(token).getBody();
            return true;
        }catch (Exception e){
            return false;
        }
    }
}














